package ch.connection;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Calendar;

/** Classe per la gestione della singola richiesta SMTP
 * 
 * @author Giovanni Franza - GPLv3 - 8/6/2011
 *
 */

public class SMTPWorker extends SMTP {

	private Socket socket;
	private SMTP smtp;
	private int state=0;
	private ch.mailbox.User user;
	
	/** Construttore .
	 *
	 * @param socket - socket su cui opera
	 * @param pop - riferimenti al gestore di protocollo
	 * 
	 */

	public SMTPWorker( Socket socket, SMTP smtp ) {
		this.socket = socket;
		this.smtp = smtp;
	}

	/** Il run fa tutto il lavoro.
	 *
	 */

	public void run() {
		try {
		    // Create streams to securely send and receive data to the client
			BufferedReader in = new BufferedReader( new InputStreamReader( socket.getInputStream() ) );				
			OutputStream out = socket.getOutputStream();	
		    // Read from in and write to out...
			String page= new String( "\n" );
		    StateManager sm = new StateManager(smtp.getStateManager());
		    out.write( sm.getWelcome().getBytes() );
		    for( ;; ) {
			    for( ;; ) {
			    	String request = in.readLine();
			    	if( request.toUpperCase().startsWith("HELO") || request.toUpperCase().startsWith("EHLO") ) {
			    		request="helo";
			    	}
			    	if( request == null || request.equals("") ){
			    		page = page.concat( "\n" );
			    		break;
			    	}
			    	sm.nextHop( request, state );
			    	out.write( sm.getResponse().getBytes() );
			    	if( sm.error() ) {
			    		break;
			    	}
			    	page = page.concat( request + "\n" );
			    }
			    if( !sm.finishedOk() ) {
			    	break;
			    }
		    	for( ;; ) {
		    		String a = in.readLine();
		    		if( a == null || a.equals( "." )  ) {
		    		    out.write( sm.getBye().getBytes() );		    			
		    			break;
		    		}
		    		page = page.concat( a + "\n" );		    	
		    	}
			    user = (ch.mailbox.User) sm.getUser();
			    if( user !=null ) {
			    	System.out.println( Calendar.getInstance().getTime().toString() + " New Mail for " + user.getEmailAddress() );
			    	user.addMessage( page );
			    }
		    }
		    // close files
		    out.close();
		    in.close();
		} catch(IOException e) {
			System.out.println(e);
		}
	}
}

